package com.kylin.common.core.validator;

import com.kylin.common.core.exception.CheckException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 对象验证器
 *
 * @author wuhao
 * @version 1.0 - 2020-03-14
 */
public class BeanValidator {

    private BeanValidator() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 验证某个bean的参数
     * 参考 https://blog.csdn.net/qq_28033239/article/details/86740861
     * @param object
     */
    public static <T> void validate(T object) {
        //获得验证器
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        //执行验证
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(object);
        if (!constraintViolations.isEmpty()) {
            List<String> message = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
            //不需要输出字段的英文名
            throw new ValidationException(String.format("%s:[%s]", CheckException.CHECK_INCORRECT_FORMAT, String.join("," , message)));
        }
    }
}
